// pages/auth/index.js

import { request } from '../../request/index.js'
import regeneratorRuntime from '../../lib/runtime/runtime'
import { login } from "../../utils/asyncWx.js"

Page({
  data: {

  },
  onLoad: function (options) {

  },

  //点击 获取授权按钮
  async handleGetUserInfo(e){
    try {

      //console.log(e) 

      //1 从事件源对象e 中 取出 用户信息
      const {encryptedData,rawData,iv,signature} = e.detail

      //2 获取小程序登录后的code值
      const { code } = await login()
      //console.log(code)

      //3 整合 请求参数
      const loginParams = {encryptedData,rawData,iv,signature,code}

      //4 发送请求 获取用户的token
      let { token } = await request({
        url:'/users/wxlogin',
        data:loginParams,
        method:'POST'
      })

      console.log(token)  //因为是个人级小程序账号 无法请求到token值 undefined

      //使用网友提供的token值
      if(!token){
        token = 'BearereyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOjIzLCJpYXQiOjE1NjQ3MzAwNzksImV4cCI6MTAwMTU2NDczMDA3OH0.YPt-XeLnjV-_1ITaXGY2FhxmCe4NvXuRnRB8OMCfnPo'
      }

      console.log(token) 

      //5 把token存入缓存中 同时跳转回上一个页面
      wx.setStorageSync("token", token);
      wx.navigateBack({
        delta: 1
      })

    } catch (error) {
      console.log(error)
    }
  }
})

